package cn.lingyangwl.agile.pay.pay.listener;

import cn.lingyangwl.agile.pay.common.model.mq.PayOrderCloseMQ;
import cn.lingyangwl.framework.mq.base.manager.MqManager;
import cn.lingyangwl.agile.pay.pay.process.ChannelPayOrderProcess;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 订单超时处理
 * 死信交换机
 * 定义死信队列
 *
 * @author shenguangyang
 */
@Component
@RabbitListener(queues = PayOrderCloseMQ.DELAY_QUEUE)
public class OrderCloseListener {
    private static final Logger log = LoggerFactory.getLogger(OrderCloseListener.class);

    @Resource
    private MqManager mqManager;

    @Resource
    private ChannelPayOrderProcess channelPayOrderProcess;

    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) {
        try {
            log.info("开始执行关单业务, msg: {}", msg);
            PayOrderCloseMQ.MsgPayload msgPayload = PayOrderCloseMQ.parse(msg);
            // 判断是否重复消费
            if (mqManager.isConsumed(msgPayload.getMsgId())) {
                log.warn("message {} are repeatedly consumed, do not perform business", msgPayload.getMsgId());
                return;
            }
            mqManager.markConsumed(msgPayload.getMsgId());
            channelPayOrderProcess.processClosePayOrder(msgPayload.getPayOrderNo(), true);
            log.info("{}", msgPayload);
        } catch (Exception e) {
            if (e instanceof NullPointerException) {
                e.printStackTrace();
            }
            log.error("exec fail: {}", e.getMessage());
            throw e;
        }
    }
}
